// 可能是我的node版本问题，不用严格模式使用ES6语法会报错
"use strict";
const Git = require("nodegit");
const Clone = Git.Clone.clone;
const cloneOptions = require('../git/cloneOptions');
const path = require('path');
const process = require('process');
const builder = require('../response/rest.result.builder')
const fs = require('fs')
const common = require('../git/common');
const _ = require('underscore');

/************** 创建(create) 读取(get) 更新(update) 删除(delete) **************/

module.exports = {
  login: function (req, res, next) {
    const params = req.body;
    console.log(req.body)
    fs.exists(params.filePath, function (exists) {
      if(exists){
        builder.buildSuccessResultInfoWithData(res, path.join(process.cwd(), params.filePath));
      }
      if(!exists){
        Clone(
          params.url,
          `${params.tmp_dir}/${params.name}`,
          cloneOptions
        )
          .then((repo) => {
            builder.buildSuccessResultInfoWithData(res,path.join(process.cwd(), params.filePath));
          })
          .catch((e) => {
            console.log(e.message);
            console.log(e.stack);
            builder.buildFailedResultInfoWithMsg(res,"400",e.message);
          });
      }
    })
  },
  commit: function (req, res, next) {
    const params = req.body;
    let repo;
    let index;
    let oid;
// api 说明
    /*
     Repository.open	: 打开本地仓库
     Repository.createCommit	: 创建commit
     Index.write 	: 将Index.addByPath的内容写进Index
     Index.writeTree : 配置Index.write一起使用, 将文件写入到tree(git概念)里面
     */

    console.log(params.add_commit_filename)
    Git.Repository.open(params.test_git_path)
      .then((repoResult) => (repo = repoResult))
      .then(() => repo.refreshIndex())
      .then((indexResult) => index = indexResult)
      .then(() => {
        return fs.writeFileSync(
          params.add_commit_filename,
          req.query.commit
        );
      })
      .then(() => repo.refreshIndex())
      .then((indexResult) => (index = indexResult))
      .then(() => index.addAll())
      .then(() => index.write())
      .then(() => index.writeTree())
      // 注释以下行可以调试只add而不commit的情况
      .then((oidResult) => {
        oid = oidResult;
        return Git.Reference.nameToId(repo, 'HEAD');
      })
      .then((head) => repo.getCommit(head))
      .then((parent) => {
        let commit_msg = req.query.commit;

        return repo.createCommit(
          'HEAD',
          common.get_commiter_sign(params),
          common.get_commiter_sign(params),
          commit_msg,
          oid,
          [parent]
        );
      })
      .done((commitId) => {
        repo.free();
        builder.buildSuccessResultInfoWithData(res, {commitId: commitId});
        console.log('New Commit: ', commitId);
      });
  },
  push: function (req, res, next) {
    const params = req.body;
    let repo;
    Git.Repository.open(params.cur_git_path)
      .then((repoResult) => (repo = repoResult))
      .then(() => Git.Remote.lookup(repo, 'origin'))
      .then((remote) => {
        return remote.push(
          ['refs/heads/master:refs/heads/master'],
          {
            callbacks: {
              credentials: (url, userName) => {
                return Git.Cred.userpassPlaintextNew(params.account, params.password);
              },
              certificateCheck: () => {
                return 1;
              }
            }
          }
        );
      })
      .then(() => {
        console.log('push done');
        builder.buildSuccessResultInfoWithData(res, '提交成功');
        repo.free();
      })
      .catch((e) => builder.buildFailedResultInfoWithMsg(res, 400, e));
  }
};
